package com.longview.io.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.longview.io.common.config.Global;
import com.longview.io.modules.sms.dao.SmsInfoDao;
import com.longview.io.modules.sms.entity.SmsInfo;
import com.longview.io.modules.sys.utils.DictUtils;

public class SmsUtils {
	
	private static Logger logger = LoggerFactory.getLogger(SmsUtils.class);
	private static SmsInfoDao smsDao = SpringContextHolder.getBean(SmsInfoDao.class);
	public static void main(String arg[])
	{
		int ret = SmsSend("15034793376");
		System.out.print(ret);
	}
	
	public static int SmsSend(String mobile)
	{
		int ret = -1;
		String vCode = getRandNum(6);
		String url = Global.getSmsUrl();
		String UserName=Global.getSmsUserName();					//用户名
		String UserPass=Global.getSmsPassword();				//密码
		String content=Global.getSmsContent().replace("#", vCode);	//new String(s.getBytes(),"GBK");
		//String Subid = getRandNum(9);	//扩展号
		try {
			content = URLEncoder.encode(content,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("发送验证码:"+mobile + "=【"+vCode+"】");
		url = url +"?"+"UserName="+UserName+"&UserPass="+UserPass+"&Content="+content+"&Mobile="+mobile+"&Subid=";
		String resMsg = httpGetSend(url,"UTF-8");
		String retAry[] = resMsg.split(",");
		logger.info("短信服务器返回:"+mobile + "=响应【"+resMsg+"】");
		logger.info("验证码发送:"+mobile + "=响应【"+DictUtils.getDictLabel(retAry[0], "sms_res_code", "返回码不存在")+"】");
		if(retAry[0].compareTo("03") == 0)//成功
			ret = 0;
		return ret;
	}

	public static int SmsSend(SmsInfo smsInfo)
	{
		int ret = -1;
		String vCode = getRandNum(6);
		String url = Global.getSmsUrl();
		String UserName=Global.getSmsUserName();					//用户名
		String UserPass=Global.getSmsPassword();				//密码
		String content=Global.getSmsContent().replace("#", vCode);	//new String(s.getBytes(),"GBK");
		String Subid = getRandNum(9);	//扩展号
		try {
			content = URLEncoder.encode(content,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("发送验证码:"+smsInfo.getMobile() + "=【"+vCode+"】");
		url = url +"?"+"UserName="+UserName+"&UserPass="+UserPass+"&Content="+content+"&Mobile="+smsInfo.getMobile()+"&Subid="+Subid;
		String resMsg = httpGetSend(url,"UTF-8");
		String retAry[] = resMsg.split(",");
		logger.info("短信服务器返回:"+smsInfo.getMobile() + "=响应【"+resMsg+"】");
		logger.info("验证码发送:"+smsInfo.getMobile() + "=响应【"+DictUtils.getDictLabel(retAry[0], "sms_res_code", "返回码不存在")+"】");
		if(retAry[0].compareTo("03") == 0)//成功
		{
			ret = 0;
			//插入验证码
			smsInfo.preInsert();
			smsInfo.setVCode(vCode);
			smsDao.insert(smsInfo);
		}
		return ret;
	}
	public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }
	
	public  static int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }
	
	public static String httpGetSend(String snedUrl,String encoded)
	{
		String urlPath = snedUrl;
		StringBuffer sbf = new StringBuffer("");
		BufferedReader reader = null;
		HttpURLConnection uc = null;
		
			try {
				URL url = new URL(urlPath);
				uc = (HttpURLConnection) url.openConnection();
				uc.setConnectTimeout(30000);
				uc.setReadTimeout(30000);
				uc.setRequestMethod("GET");
				uc.setDoOutput(true);
				uc.setDoInput(true);
				
				uc.connect();
				reader = new BufferedReader(new InputStreamReader(uc.getInputStream())); // 读取服务器响应信息
				String line;
				while ((line = reader.readLine()) != null) {
					sbf.append(line);
				}
				reader.close();
				uc.disconnect();
				return sbf.toString();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					reader.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		return null;
	}
}
